package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zcf
 */
@Service
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Resource
    private UserMapper userMapper;
    @Resource
    private WeChatProperties weChatProperties;
    // 用户小程序登录
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1.调用微信登录接口
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid() );
        map.put("secret",weChatProperties.getSecret() );
        map.put("js_code",userLoginDTO.getCode() );
        map.put("grant_type","authorization_code" );
        String s = HttpClientUtil.doGet(WX_LOGIN_URL,map);
        if(!StringUtils.hasLength(s)){
            throw new BaseException(MessageConstant.LOGIN_FAILED);
        }
        //2.解析返回的Json字符串
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");//微信用户唯一标识
        if(!StringUtils.hasLength(openid)){
            throw new BaseException(MessageConstant.LOGIN_FAILED);
        }

        //判断用户是否是第一次注册,还需要插入
       User user= userMapper.getByOpenid(openid);
        if(user==null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }
      return user;
    }
}
